package com.tetris;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Size;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.common.GameBoard;

// 主活动
public class MainActivity extends Activity implements Callback, GameBoard.Callback, View.OnTouchListener {
    private Button mButtonMusic;        // "音乐"按钮
    private Button mButtonPause;        // "暂停"按钮
    private Game mGame;                 // 游戏
    private TextView mLabelDifficulty;  // 难度值标签
    private TextView mLabelScore;       // 得分值标签

    /**
     * 自定义事件的响应方法。
     * @param message   事件
     * @return 事件在此被处理则返回 true，否则返回 false
     */
    @Override
    public boolean handleMessage(Message message) {
        switch (message.what) {
            case Const.UM_DIFFICULTY_UP:
                this.onDifficultyUp(message.arg1);
                return true;
            case Const.UM_GAME_OVER:
                this.onGameOver((Boolean)message.obj);
                return true;
            case Const.UM_SCORE:
                this.onScore(message.arg1);
                return true;
        }
        return false;
    }

    /**
     * "播放音乐"按钮的单击响应方法。
     * @param view  按钮
     */
    public void onButtonMusicClicked(View view) {
        final boolean playingMusic = mGame.playMusic();
        if (playingMusic) {
            mButtonMusic.setBackgroundResource(R.drawable.button_music_stop_state);
        } else {
            mButtonMusic.setBackgroundResource(R.drawable.button_music_play_state);
        }
    }

    /**
     * "暂停"按钮的单击响应方法。
     * @param view  按钮
     */
    public void onButtonPauseClicked(View view) {
        mGame.pause();
        final Game.Status status = mGame.getStatus();
        if (status == Game.Status.PAUSED) {
            mButtonPause.setBackgroundResource(R.drawable.button_resume_state);
        } else if (status == Game.Status.PLAYING) {
            mButtonPause.setBackgroundResource(R.drawable.button_pause_state);
        }
    }

    /**
     * "向左"、"向右"、"变形"按钮的单击响应方法。
     * @param view  按钮
     */
    public void onButtonPlayClicked(View view) {
        final int id = view.getId();
        if (id == R.id.IDC_BUTTON_LEFT) {
            mGame.moveBlockLeft();
        } else if (id == R.id.IDC_BUTTON_RIGHT) {
            mGame.moveBlockRight();
        } else if (id == R.id.IDC_BUTTON_TRANSFORM) {
            mGame.transformBlock();
        }
    }

    /**
     * "开始"按钮的单击响应方法。
     * @param view  按钮
     */
    public void onButtonStartClicked(View view) {
        // 游戏开始
        mGame.start();

        // 设置按钮状态
        mButtonPause.setEnabled(true);

        // 设置按钮图片
        mButtonPause.setBackgroundResource(R.drawable.button_pause_state);

        // 设置状态栏文字
        this.onDifficultyUp(1);
        this.onScore(0);
    }

    /**
     * 创建事件的响应方法。
     * @param savedInstanceState    保存的实例状态
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.activity_main);

        final GameBoard gameBoard = super.findViewById(R.id.IDC_GAME_BOARD);
        gameBoard.setCallback(this);
        final GameBoard preview = super.findViewById(R.id.IDC_PREVIEW);
        preview.setCallback(this);
    }

    /**
     * 难度增加事件的响应方法。
     * @param difficulty    难度
     */
    private void onDifficultyUp(int difficulty) {
        mLabelDifficulty.setText(super.getString(R.string.IDS_DIFFICULTY, difficulty));
    }

    /**
     * 游戏区域度量尺寸事件的响应方法。
     * @param gameBoard         游戏区域
     * @param widthMeasureSpec  父控件指定的宽度值
     * @param heightMeasureSpec 父控件指定的高度值
     * @return 游戏区域的尺寸
     */
    @Override
    public Size onGameBoardMeasure(View gameBoard, int widthMeasureSpec, int heightMeasureSpec) {
        // 获取屏幕尺寸
        final DisplayMetrics displayMetrics = super.getResources().getDisplayMetrics();

        // 计算格的尺寸
        if (Const.GRID_SIZE == 0) {
            Const.GRID_SIZE = displayMetrics.widthPixels / (Const.PADDING_LEFT + Const.GAME_BOARD_GRID_COUNT_H +
                Const.PADDING_MIDDLE + Const.PREVIEW_GRID_COUNT_H + Const.PADDING_RIGHT);
        }

        int width;
        int height;

        if (gameBoard.getId() == R.id.IDC_GAME_BOARD) {
            // 计算游戏区域尺寸
            width = Const.GRID_SIZE * Const.GAME_BOARD_GRID_COUNT_H;
            height = Const.GRID_SIZE * Const.GAME_BOARD_GRID_COUNT_V;

            // 设置自身与左、右边控件的间距
            final RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)gameBoard.getLayoutParams();
            layoutParams.leftMargin = Const.GRID_SIZE * Const.PADDING_LEFT;
            layoutParams.rightMargin = Const.GRID_SIZE * Const.PADDING_MIDDLE;
            gameBoard.setLayoutParams(layoutParams);
        } else {
            // 计算预览区域尺寸
            width = Const.GRID_SIZE * Const.PREVIEW_GRID_COUNT_H;
            height = Const.GRID_SIZE * Const.PREVIEW_GRID_COUNT_V;

            // 设置自身与右边控件的间距
            final RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)gameBoard.getLayoutParams();
            layoutParams.rightMargin = Const.GRID_SIZE * Const.PADDING_RIGHT;
            gameBoard.setLayoutParams(layoutParams);
        }

        return new Size(width, height);
    }

    /**
     * 游戏结束事件的响应方法。
     * @param isWon  胜利则为 true，否则为 false
     */
    private void onGameOver(boolean isWon) {
        if (isWon) {
            Toast.makeText(this, super.getString(R.string.IDS_WON), Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, super.getString(R.string.IDS_LOST), Toast.LENGTH_LONG).show();
        }
        mButtonPause.setEnabled(false);
    }

    /**
     * 暂停事件的响应方法。
     */
    @Override
    public void onPause() {
        super.onPause();

        final Game.Status status = mGame.getStatus();
        if (status == Game.Status.PLAYING) {
            this.onButtonPauseClicked(null);
        }
    }

    /**
     * 得分事件的响应方法。
     * @param score 得分
     */
    private void onScore(int score) {
        mLabelScore.setText(super.getString(R.string.IDS_SCORE, score));
    }

    /**
     * 触屏事件的响应方法。
     * @param view  用户触摸的控件
     * @param e     事件相关信息
     * @return 事件在此被处理则返回 true，否则返回 false
     */
    @Override
    public boolean onTouch(View view, MotionEvent e) {
        mGame.moveBlockDown();
        return view.performClick();
    }

    /**
     * 焦点变化事件的响应方法。
     * @param hasFocus  获得焦点则返回 true，否则返回 false
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (mGame == null) {
            // 设置控件
            mButtonPause = super.findViewById(R.id.IDC_BUTTON_PAUSE);
            mButtonPause.setEnabled(false);
            mButtonMusic = super.findViewById(R.id.IDC_BUTTON_MUSIC);
            super.findViewById(R.id.IDC_BUTTON_DOWN).setOnTouchListener(this);
            mLabelDifficulty = super.findViewById(R.id.IDC_LABEL_DIFFICULTY);
            mLabelDifficulty.setText(super.getString(R.string.IDS_DIFFICULTY, 1));
            mLabelScore = super.findViewById(R.id.IDC_LABEL_SCORE);
            mLabelScore.setText(super.getString(R.string.IDS_SCORE, 0));

            // 创建游戏区域
            final GameBoard gameBoard = super.findViewById(R.id.IDC_GAME_BOARD);

            // 创建预览区域
            final GameBoard preview = super.findViewById(R.id.IDC_PREVIEW);

            // 创建游戏
            mGame = new Game(this, gameBoard, gameBoard.getDrawer(), preview, preview.getDrawer());
        }
    }
}
